/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iss.examsys.ejb;

import java.util.Collection;
import java.util.Date;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.faces.application.FacesMessage;
import org.primefaces.push.EventBus;
import org.primefaces.push.EventBusFactory;

/**
 *
 * @author Quek Ting Hong
 */
@Stateless
public class ExamTimerSessionBean {
    
    private final static String EXAM_TIMESUP_CHANNEL = "/examtimesup";

    
    @Resource
    TimerService timerService;
    private Logger logger = Logger.getLogger(
            "com.iss.examsys.ejb.ExamTimerSessionBean");

    public void createTimer(long intervalDuration) {
        TimerConfig timerConfig = new TimerConfig();
        timerConfig.setInfo("123");
        timerConfig.setPersistent(true);
        
        timerService.createSingleActionTimer(intervalDuration, timerConfig);
    }
    
    public void createTimer(Date triggerDate, Long examSessionId) {
        TimerConfig timerConfig = new TimerConfig();
        timerConfig.setInfo(examSessionId);
        timerConfig.setPersistent(true);
        
        timerService.createSingleActionTimer(triggerDate, timerConfig);
    }
    
    public void cancelTimer(String examId) {
        
        Collection<Timer> timers = timerService.getAllTimers();
        
        for(Timer t : timers){
            if(t.getInfo().equals(examId)){
                t.cancel();
            }
        }
        
    }
    
    @Timeout
    public void programmaticTimeout(Timer timer) {
        
        logger.info("Programmatic timeout occurred." + timer.getInfo());
        
        EventBus eventBus = EventBusFactory.getDefault().eventBus();
        eventBus.publish(EXAM_TIMESUP_CHANNEL, new FacesMessage("Times Up"));
    }
}
